<template>
  <div class="workflow-process">
    <el-card>
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="流程名称">
            <el-input v-model="searchForm.name" placeholder="请输入流程名称" clearable />
          </el-form-item>
          <el-form-item label="流程类型">
            <el-select v-model="searchForm.type" placeholder="请选择流程类型" clearable>
              <el-option label="生产审批" value="production" />
              <el-option label="采购审批" value="purchase" />
              <el-option label="财务审批" value="finance" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
            <el-button type="success" @click="handleAdd">新增流程</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <el-table :data="tableData" border stripe v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="流程名称" />
        <el-table-column prop="type" label="流程类型">
          <template #default="scope">
            <el-tag v-if="scope.row.type === 'production'" type="success">生产审批</el-tag>
            <el-tag v-else-if="scope.row.type === 'purchase'" type="warning">采购审批</el-tag>
            <el-tag v-else-if="scope.row.type === 'finance'" type="danger">财务审批</el-tag>
            <el-tag v-else type="info">{{ scope.row.type }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 1" type="success">启用</el-tag>
            <el-tag v-else type="danger">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="success" size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="800px"
        @close="handleDialogClose"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="流程名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入流程名称" />
        </el-form-item>
        <el-form-item label="流程类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择流程类型">
            <el-option label="生产审批" value="production" />
            <el-option label="采购审批" value="purchase" />
            <el-option label="财务审批" value="finance" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>

        <!-- 节点配置 -->
        <el-form-item label="流程节点">
          <div class="nodes-container">
            <div v-for="(node, index) in form.nodes" :key="index" class="node-item">
              <el-card>
                <template #header>
                  <div class="node-header">
                    <span>节点 {{ index + 1 }}</span>
                    <el-button type="danger" size="small" @click="removeNode(index)">删除</el-button>
                  </div>
                </template>
                <el-form-item label="节点名称" :prop="`nodes.${index}.name`" :rules="{ required: true, message: '请输入节点名称', trigger: 'blur' }">
                  <el-input v-model="node.name" placeholder="请输入节点名称" />
                </el-form-item>
                <el-form-item label="审批人" :prop="`nodes.${index}.approverId`" :rules="{ required: true, message: '请选择审批人', trigger: 'change' }">
                  <el-select v-model="node.approverId" placeholder="请选择审批人" filterable>
                    <el-option
                        v-for="user in userList"
                        :key="user.id"
                        :label="user.name || user.username"
                        :value="user.id"
                    >
                      <span>{{ user.name || user.username }}</span>
                      <span style="float: right; color: #8492a6; font-size: 13px">{{ user.username }}</span>
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="备注">
                  <el-input v-model="node.remark" placeholder="请输入备注" />
                </el-form-item>
              </el-card>
            </div>
            <el-button type="primary" @click="addNode">添加节点</el-button>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 查看对话框 -->
    <el-dialog v-model="viewDialogVisible" title="流程详情" width="600px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="流程名称">{{ viewForm.name }}</el-descriptions-item>
        <el-descriptions-item label="流程类型">
          <el-tag v-if="viewForm.type === 'production'" type="success">生产审批</el-tag>
          <el-tag v-else-if="viewForm.type === 'purchase'" type="warning">采购审批</el-tag>
          <el-tag v-else-if="viewForm.type === 'finance'" type="danger">财务审批</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag v-if="viewForm.status === 1" type="success">启用</el-tag>
          <el-tag v-else type="danger">禁用</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="备注">{{ viewForm.remark }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ viewForm.createTime }}</el-descriptions-item>
      </el-descriptions>

      <div class="nodes-list">
        <h4>流程节点</h4>
        <el-table :data="viewForm.nodes" border>
          <el-table-column prop="name" label="节点名称" />
          <el-table-column prop="approverId" label="审批人ID" />
          <el-table-column prop="sort" label="排序" />
          <el-table-column prop="remark" label="备注" />
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { workflowProcessApi } from '@/api/production/workflow'
import { userApi } from '@/api/production/user'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()

// 用户列表
const userList = ref([])

// 搜索表单
const searchForm = reactive({
  name: '',
  type: ''
})

// 分页数据
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 表格数据
const tableData = ref([])

// 表单数据
const form = reactive({
  id: null,
  name: '',
  type: '',
  status: 1,
  remark: '',
  nodes: []
})

// 查看表单数据
const viewForm = reactive({
  id: null,
  name: '',
  type: '',
  status: 1,
  remark: '',
  createTime: '',
  nodes: []
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入流程名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择流程类型', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 获取用户列表
const getUserList = async () => {
  try {
    const response = await userApi.list()
    
    // 检查响应格式
    if (response && response.code === 200) {
      userList.value = response.data || []
    } else if (response && Array.isArray(response)) {
      // 直接返回数组的情况
      userList.value = response || []
    } else {
      console.error('获取用户列表失败:', response)
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
  }
}

// 获取数据
const getData = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.current,
      size: pagination.size,
      ...searchForm
    }
    console.log('请求参数:', params)
    const response = await workflowProcessApi.list(params)
    console.log('API返回数据:', response)

    // 检查返回数据的结构
    if (response && response.records) {
      // 直接使用返回的数据（MyBatis-Plus分页格式）
      console.log('处理后的数据:', response)
      console.log('记录列表:', response.records)
      console.log('总记录数:', response.total)
      tableData.value = response.records || []
      pagination.total = response.total || 0
      pagination.current = response.current || 1
      pagination.size = response.size || 10
    } else if (response && response.code === 200 && response.data) {
      // 标准API响应格式
      console.log('处理后的数据:', response)
      console.log('记录列表:', response.data.records)
      console.log('总记录数:', response.data.total)
      tableData.value = response.data.records || []
      pagination.total = response.data.total || 0
      pagination.current = response.data.current || 1
      pagination.size = response.data.size || 10
    } else {
      console.error('API返回错误:', response)
      ElMessage.error('获取数据失败：数据格式不正确')
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败：' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  getData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    type: ''
  })
  handleSearch()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增流程'
  Object.assign(form, {
    id: null,
    name: '',
    type: '',
    status: 1,
    remark: '',
    nodes: []
  })

  // 自动添加默认节点
  const currentUser = getCurrentUser()
  const approverId = currentUser ? getUserIdByUsername(currentUser.username) : null
  if (approverId) {
    form.nodes.push({
      name: '默认审批节点',
      approverId,
      remark: '系统自动生成的审批节点'
    })
  }

  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑流程'
  Object.assign(form, {
    id: row.id,
    name: row.name,
    type: row.type,
    status: row.status,
    remark: row.remark,
    nodes: []
  })
  // 获取节点数据
  getProcessNodes(row.id)
  dialogVisible.value = true
}

// 获取流程节点
const getProcessNodes = async (id) => {
  try {
    const response = await workflowProcessApi.getById(id)
    
    // 检查响应格式
    if (response && response.code === 200 && response.data) {
      form.nodes = response.data.nodes || []
    } else if (response && response.nodes) {
      // 直接返回节点数据的情况
      form.nodes = response.nodes || []
    } else {
      console.error('获取节点数据失败:', response)
      ElMessage.error('获取节点数据失败')
    }
  } catch (error) {
    console.error('获取节点数据失败:', error)
    ElMessage.error('获取节点数据失败：' + (error.message || '未知错误'))
  }
}

// 查看
const handleView = async (row) => {
  try {
    const response = await workflowProcessApi.getById(row.id)
    
    // 检查响应格式
    if (response && response.code === 200 && response.data) {
      Object.assign(viewForm, response.data)
      viewDialogVisible.value = true
    } else if (response && response.id) {
      // 直接返回流程数据的情况
      Object.assign(viewForm, response)
      viewDialogVisible.value = true
    } else {
      ElMessage.error('获取详情失败：数据格式不正确')
    }
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败：' + (error.message || '未知错误'))
  }
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该流程吗？', '提示', {
      type: 'warning'
    })
    const response = await workflowProcessApi.delete(row.id)
    
    // 检查响应格式
    if (response && response.code === 200) {
      ElMessage.success('删除成功')
      getData()
    } else if (response && response.success) {
      // 兼容其他响应格式
      ElMessage.success('删除成功')
      getData()
    } else {
      ElMessage.error(response?.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败：' + (error.message || '未知错误'))
    }
  }
}

// 获取当前用户信息
const getCurrentUser = () => {
  try {
    const username = localStorage.getItem('username')
    return username ? { username } : null
  } catch (error) {
    console.error('获取用户信息失败:', error)
    return null
  }
}

// 根据username查找用户id
const getUserIdByUsername = (username) => {
  const user = userList.value.find(u => u.username === username)
  return user ? user.id : null
}

// 添加节点
const addNode = () => {
  const currentUser = getCurrentUser()
  const approverId = currentUser ? getUserIdByUsername(currentUser.username) : null
  form.nodes.push({
    name: '',
    approverId,
    remark: ''
  })
}

// 删除节点
const removeNode = (index) => {
  form.nodes.splice(index, 1)
}

// 初始化时自动添加一个节点
const initDefaultNode = () => {
  const currentUser = getCurrentUser()
  const approverId = currentUser ? getUserIdByUsername(currentUser.username) : null
  if (approverId && form.nodes.length === 0) {
    form.nodes.push({
      name: '默认审批节点',
      approverId,
      remark: '系统自动生成的审批节点'
    })
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    const response = form.id ? await workflowProcessApi.update(form) : await workflowProcessApi.add(form)
    
    // 检查响应格式
    if (response && response.code === 200) {
      ElMessage.success(form.id ? '更新成功' : '新增成功')
      dialogVisible.value = false
      getData()
    } else if (response && response.success) {
      // 兼容其他响应格式
      ElMessage.success(form.id ? '更新成功' : '新增成功')
      dialogVisible.value = false
      getData()
    } else {
      ElMessage.error(response?.message || '操作失败')
    }
  } catch (error) {
    console.error('表单提交失败:', error)
    ElMessage.error('操作失败：' + (error.message || '未知错误'))
  }
}

// 对话框关闭
const handleDialogClose = () => {
  formRef.value?.resetFields()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  getData()
}

// 当前页改变
const handleCurrentChange = (current) => {
  pagination.current = current
  getData()
}

// 初始化
onMounted(() => {
  getData()
  getUserList()
  initDefaultNode() // 初始化时自动添加一个节点
})
</script>

<style scoped>
.workflow-process {
  padding: 20px;
}

.search-area {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.nodes-container {
  max-height: 400px;
  overflow-y: auto;
}

.node-item {
  margin-bottom: 10px;
}

.node-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.nodes-list {
  margin-top: 20px;
}

.nodes-list h4 {
  margin-bottom: 10px;
}
</style>
